<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;
use app\common\model\Crawls;
use app\common\model\CrawlEmails;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use app\common\library\Email as Eamlib;
use app\common\model\EmsLog;
/**
 * 抓取網絡email
 */
class Email extends Api
{
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }
    /**
     * 歷史記錄
     */
    public function items($page = null,$crawl_id = null){
        $map = ['user_id' => $this->auth->id,'crawl_id' => intval($crawl_id),'status' => 1];
        $items = CrawlEmails::where($map)->order('id desc')->field('id,email,created_at')->select();
        // foreach($items as $item){
        //     $item->created_at = date('M d Y, H:i A',$item->created_at);
        // }
        $this->success(__('capture successful'),$items);
    }  
    /**
     * 歷史記錄
     */
    public function list($page = null,$crawl_id = null,$status=null){
        $map = ['user_id' => $this->auth->id,'crawl_id' => intval($crawl_id)];
        $items = CrawlEmails::where($map)->order('id desc')->field('id,email,created_at')->paginate(10);
        foreach($items as $item){
            $item->created_at = date('M d Y, H:i A',$item->created_at);
        }
        $this->success(__('capture successful'),$items);
    }  
    /**
     * 刪除
     */
    public function delete($id=null){
        $map = ['user_id' => $this->auth->id,'id' => intval($id)];
        $row = CrawlEmails::where($map)->find();
        if(empty($row)){
            $this->error(__('not found'));
        }
        $row->delete();
        $this->success(__('successful'));
    } 
    /**
     * 發送郵件
     */
    public function send(){
        $subject = $this->request->post('subject');
        $content = isset($_POST['content']) ? $_POST['content'] : '';//$this->request->post('content',null,"trim");//$_POST['content'];
        $emails = $this->request->post('emails/a');
        if(empty($subject)){
            $this->error(__('Enter subject'));
        }
        $data = [];
        if(empty($content)){
            $str = file_get_contents('php://input');
            if(!empty($str)){
                $data = (array) json_decode($str, true);
                $content = isset($data['content']) ? $data['content'] : '';
                $this->request->filterExp($content);
            }
        }
        if(empty($content)){
            $this->error(__('Enter content'));
        }
        if(empty($emails)){
            $this->error(__('Enter emails'));
        }
        
        $result = null;
        try{
            $em = Eamlib::instance([]);
            $user = $this->auth->getUser();
            $result = $em->from($user['send_from_email'],$user['send_email_name'])
                    ->to($emails)
                    ->subject($subject)
                    ->message($content)->send();
            if($result !== true){
                throw new Exception($em->getMessage());
            }
        }catch(Exception $e){
            // 記錄歷史
            $this->addLog($subject,$content,$emails,$e->getMessage());
            $this->error($e->getMessage());
        }
        // 記錄歷史
        $this->addLog($subject,$content,$emails,'success');
        $this->success("send successful");
    }
    public function save($crawl_id = null){
        $map = ['user_id' => $this->auth->id,'crawl_id' => intval($crawl_id)];
        $row = CrawlEmails::where($map)->update(['status' => 1]);
        $this->success("save successful");
    }

    public function addLog($subject,$content,$emails,$error=null){
         EmsLog::create([
                'user_id' => $this->auth->id,
                'subject' => $subject,
                'content' => $content,
                'emails'  => implode(',',$emails),
                'author'  => $this->auth->nickname,
                'created_at' => time(),
                'error' => $error
            ]);
    }
}